﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Joyintech.Model.inpiao365;
using Joyintech.BLL.inpiao365;
using Joyintech.Common;
using System.IO;
using System.Text;
using System.Data;

namespace Joyintech.Admin.inpiao365.general.createhtml
{
    /// <summary>
    /// 生成内容页面
    /// </summary>
    public partial class createContent : System.Web.UI.Page
    {
        #region 页面初始化

        /// <summary>
        /// 页面初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                //加载栏目列表
                DataBindNode(0, "");
            }
        }

        #endregion

        #region 加载栏目列表

        /// <summary>
        /// 加载栏目列表
        /// </summary>
        /// <param name="ParentId"></param>
        private void DataBindNode(int ParentId, string strFront)
        {
            List<systemNode> list = new List<systemNode>();

            list = new systemNode_BLL().GetModelList("ParentID=" + ParentId + " order by NodeOrder");

            if (list != null && list.Count > 0)
            {
                strFront += "-";

                foreach (systemNode nodeModel in list)
                {
                    ListItem item = new ListItem(strFront + nodeModel.NodeName, nodeModel.NodeID.ToString());

                    this.listSystemNode.Items.Add(item);

                    DataBindNode(nodeModel.NodeID, strFront);
                }
            }
        }

        #endregion

        #region 创建内容页面

        /// <summary>
        /// 创建内容页面
        /// </summary>
        private void Create()
        {
            string selectedNodeId = string.Empty;

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    selectedNodeId += item.Value + ",";
                    break;
                }
            }

            if (selectedNodeId == "")
            {
                MessageBox.Show(this, "没有选择需要生成的栏目！");
                return;
            }

            pageSplit_BLL pageBll = new pageSplit_BLL();

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    int NodeId = Convert.ToInt32(item.Value);

                    systemNode nodeModel = new systemNode_BLL().GetModel(NodeId);

                    //取得内容模板
                    systemTemplate model = new systemTemplate_BLL().GetModel(nodeModel.ContentTemplateID.Value);

                    if (model == null)
                    {
                        MessageBox.Show(this, "页面生成已停止，没有检索到栏目\"" + item.Text + "\"对应的模板（模板编号：" + model.TemplateId + "）！");
                        return;
                    }

                    string templatefileName = Server.MapPath("../../templates/" + model.RelatedFileName);

                    if (model.TemplateType == "ChannelTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/channel/" + model.RelatedFileName);
                    }
                    else if (model.TemplateType == "ContentTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/content/" + model.RelatedFileName);
                    }

                    //检查模板文件是否存在
                    if (!Utils.FileExists(templatefileName))
                    {
                        MessageBox.Show(this, "栏目\"" + item.Text + "\"对应的模板文件\"" + model.RelatedFileName + "\"不存在，可能已被移除，请确认！");
                        return;
                    }

                    VelocityHelper vh = new VelocityHelper();
                    vh.Init(@"~/templates/content/");

                    string bllName = ConfigHelper.GetConfigString("BLL");
                    System.Reflection.Assembly BLL = System.Reflection.Assembly.Load(bllName);

                    Type[] types = BLL.GetTypes();

                    // 遍历程序集中的类
                    foreach (Type type in types)
                    {
                        string className = type.ToString().Replace(bllName + ".", "");

                        object stu = type.Assembly.CreateInstance(type.ToString());

                        //添加页面操作类BLL
                        vh.Put(className, stu);
                    }

                    //获取当前栏目内容数据集
                    DataSet ds = new DataSet();

                    ds = pageBll.GetList(nodeModel.SelectTable);

                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        //返回生成多个列表页面
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            //页面内容实体
                            vh.Put("content", dr);

                            //页面栏目实体
                            vh.Put("channel", nodeModel);

                            string html = vh.Display(model.RelatedFileName);

                            //string directory = ConfigHelper.GetConfigString("ContentPath");

                            string directory = model.FileCreatePath + "\\";

                            //判断栏目页面文件夹是否存在，如果不存在则创建
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            //内容页面名称，默认只有一页
                            string fileName = directory + "\\" + dr[nodeModel.ContentTableKey].ToString() + model.CreatedFileExtName;

                            StreamWriter objSw = new StreamWriter(fileName, false, Encoding.GetEncoding(model.TemplateCharset));
                            objSw.WriteLine(html);
                            objSw.Flush();
                            objSw.Close();
                        }
                    }

                }
            }

            MessageBox.Show(this, "生成成功！");

        }

        #endregion

        #region 删除生成的栏目页面

        /// <summary>
        /// 删除生成的内容页面
        /// </summary>
        private void DeleteContentPage()
        {
            string selectedNodeId = string.Empty;

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    selectedNodeId += item.Value + ",";
                    break;
                }
            }

            if (selectedNodeId == "")
            {
                MessageBox.Show(this, "没有选择栏目！");
                return;
            }

            pageSplit_BLL pageBll = new pageSplit_BLL();

            foreach (ListItem item in this.listSystemNode.Items)
            {
                if (item.Selected)
                {
                    int NodeId = Convert.ToInt32(item.Value);

                    systemNode nodeModel = new systemNode_BLL().GetModel(NodeId);

                    //取得内容模板
                    systemTemplate model = new systemTemplate_BLL().GetModel(nodeModel.ContentTemplateID.Value);

                    if (model == null)
                    {
                        MessageBox.Show(this, "操作已停止，没有检索到栏目\"" + item.Text + "\"对应的模板（模板编号：" + model.TemplateId + "）！");
                        return;
                    }

                    string templatefileName = Server.MapPath("../../templates/" + model.RelatedFileName);

                    if (model.TemplateType == "ChannelTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/channel/" + model.RelatedFileName);
                    }
                    else if (model.TemplateType == "ContentTemplate")
                    {
                        templatefileName = Server.MapPath("../../templates/content/" + model.RelatedFileName);
                    }

                    //检查模板文件是否存在
                    if (!Utils.FileExists(templatefileName))
                    {
                        MessageBox.Show(this, "栏目\"" + item.Text + "\"对应的模板文件\"" + model.RelatedFileName + "\"不存在，可能已被移除，请确认！");
                        return;
                    }

                    VelocityHelper vh = new VelocityHelper();
                    vh.Init(@"~/templates/content/");

                    //获取当前栏目内容数据集
                    DataSet ds = new DataSet();

                    ds = pageBll.GetList(nodeModel.SelectTable);

                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    {
                        //返回生成多个列表页面
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            //string directory = ConfigHelper.GetConfigString("ContentPath");

                            string directory = model.FileCreatePath + "\\";

                            //判断栏目页面文件夹是否存在，如果不存在则创建
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            //内容页面名称，默认只有一页
                            string fileName = directory + dr[nodeModel.ContentTableKey].ToString() + model.CreatedFileExtName;

                            File.Delete(fileName);
                        }
                    }
                }
            }
        }

        #endregion

        #region 页面按钮事件

        /// <summary>
        /// 生成内容页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCreateContent_Click(object sender, EventArgs e)
        {
            Create();

            MessageBox.Show(this, "生成成功！");
        }

        /// <summary>
        /// 删除内容页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDeleteContent_Click(object sender, EventArgs e)
        {
            DeleteContentPage();

            MessageBox.Show(this, "删除成功！");
        }

        #endregion


    }
}